<?php
include '../config.php';

function createNewUser() {
	
	session_start();
	
	// Connecting, selecting database
	$mysqli = new mysqli($GLOBALS['MYSQL_HOST'], $GLOBALS['MYSQL_USERNAME'], 
			$GLOBALS['MYSQL_PASSWORD'], $GLOBALS['MYSQL_DB_NAME']);
	if ($mysqli->connect_errno) {
		$_SESSION[$GLOBALS['CU_MSG_TAG']] = $GLOBALS['DB_CONN_ERR'];
		$_SESSION[$GLOBALS['DB_CONN_ERRNO']] = $mysqli->connect_errno;
		$_SESSION[$GLOBALS['DB_CONN_ERROR']] = $mysqli->connect_error;
		return;
	}
	
	$mysqli->set_charset("utf8");
	
	$lastName = prepareString($mysqli, $_POST['lastName']);
	$name = prepareString($mysqli, $_POST['name']);
	$email = prepareString($mysqli, $_POST['email']);
	$password = randomString(10);
	
	$hash = crypt($password, $GLOBALS['PSW_SALT']);
	for ($i = 0; $i < $GLOBALS['HASHING_ITERATIONS']; ++$i)
	{
		$hash = crypt($hash . $password, $GLOBALS['PSW_SALT']);
	}
	
	if (isset($_POST['admin']))
		$admin = TRUE;
	else
		$admin = FALSE;
	
	$issuer = $_SESSION["id_issuer"];
	$query = sprintf($GLOBALS['INSERT_USER'], $lastName, $name, $email, $hash, $admin, $issuer);
	
	$result = $mysqli->query($query);
	if (!$result) {
		mysqli_free_result($result);
		$mysqli->close();
		$_SESSION[$GLOBALS['CU_MSG_TAG']] = $GLOBALS['QUERY_ERR'];
		$_SESSION[$GLOBALS['QUERY_TAG']] = $query;
		$_SESSION[$GLOBALS['QUERY_ERRNO']] = $mysqli->errno;
		$_SESSION[$GLOBALS['QUERY_ERROR']] = $mysqli->error;
		return;
	}
	
	mysqli_free_result($result);
	
	// Closing connection
	$mysqli->close();
	
	$sent = sendRegisteredEmail($email, $password, $admin);
	
	if (!$sent) {
		$_SESSION[$GLOBALS['CU_MSG_TAG']] = $GLOBALS['MAIL_ERR'];
	} else {
		$_SESSION[$GLOBALS['CU_MSG_TAG']] = $GLOBALS['MSG_OK'];
	}
	
	return;
}
?>
